import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:travel/chat/chat_flutter.dart';
import 'package:travel/chat/utils/parameter_model_set/parameter_model_set.dart';
import 'package:travel/chat/widgets/chat_view_item/chat_view_item.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

class Letter extends StatefulWidget {
  const Letter({super.key});

  @override
  State<Letter> createState() => _LetterState();
}

class _LetterState extends State<Letter> with WidgetsBindingObserver {
  String nickname = '果汁分你一半';

  double bottom = 0.0;

  TextEditingController controller = ToolsUtils.editingController('');

  FocusNode focusNode = FocusNode();

  late ChatViewWidgetController chatViewWidgetController;

  ChatViewItemAvatarModel rightAvatar = ChatViewItemAvatarModel(
      avatarSize: 40.w,
      avatarPath:
          'https://img2.baidu.com/it/u=1403316214,3492494261&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500');

  ChatViewItemAvatarModel leftAvatar = ChatViewItemAvatarModel(
    avatarSize: 40.w,
    avatarPath:
        'https://img1.baidu.com/it/u=3547412726,2113146789&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  );

  List<ChatViewItem> data = [];

  @override
  void initState() {
    initData();
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
      appBar: AppBar(
        automaticallyImplyLeading: true,
        leading: InkWell(
          onTap: Get.back,
          child: Icon(
            Icons.arrow_back_ios,
            color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
            size: 20.w,
          ),
        ),
        leadingWidth: 40.w,
        title: Text(
          nickname,
          style: StylesUtils.customTextStyle(
              color: ColorsUtils.color3333, fontSize: 18.sp, fontWeight: FontWeight.bold),
        ),
      ),
      body: buildChatBody(context),
      resizeToAvoidBottomInset: false,
      bottomNavigationBar: Padding(
        padding: EdgeInsets.only(bottom: bottom),
        child: Container(
          height: 50.h,
          padding: EdgeInsets.symmetric(horizontal: 10.w),
          decoration: const BoxDecoration(color: Colors.white),
          child: Row(
            children: [
              Expanded(
                  child: TextField(
                focusNode: focusNode,
                controller: controller,
                cursorWidth: 2.0,
                cursorRadius: const Radius.circular(2),
                cursorColor: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                style: StylesUtils.customTextStyle(fontSize: 15.sp, color: ColorsUtils.color3333),
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(15),
                    borderSide: BorderSide.none,
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(15),
                    borderSide: BorderSide.none,
                  ),
                  hintText: '发送消息...',
                  contentPadding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
                  isCollapsed: true,
                  isDense: true,
                  fillColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF8f8),
                  filled: true,
                  hintStyle:
                      StylesUtils.customTextStyle(color: ColorsUtils.color9999, fontSize: 15.sp),
                ),
              )),
              Align(
                child: TextButton(
                    onPressed: onSend,
                    child: Text(
                      '发送',
                      style: StylesUtils.customTextStyle(
                          fontSize: 16.sp, color: ColorsUtils.color3333),
                    )),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void didChangeMetrics() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        bottom = MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).viewInsets.bottom;
      });
    });
    super.didChangeMetrics();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    focusNode.dispose();
    controller.dispose();
    super.dispose();
  }

  void initData() {
    if (Get.arguments != null) {
      nickname = Get.arguments['nickname'];
    }
    data.add(ChatViewItem(
      itemBody: '您好，驴友小姐姐，在吗？',
      avatarModel: rightAvatar,
      backgroundColor: ColorsUtils.rgba(220, 232, 255),
      textTypeModel: ChatViewItemTextTypeModel(
          itemBodyTextStyle:
              StylesUtils.customTextStyle(fontSize: 16.sp, color: ColorsUtils.color0000)),
    ));
    data.add(ChatViewItem(
      senderRight: false,
      itemBody: '我在的亲，请问有什么需要帮助的吗？',
      avatarModel: leftAvatar,
      textTypeModel: ChatViewItemTextTypeModel(
          itemBodyTextStyle:
              StylesUtils.customTextStyle(fontSize: 16.sp, color: ColorsUtils.color0000)),
    ));
  }

  void onSend() {
    setState(() {
      chatViewWidgetController.add(ChatViewItem(
        itemBody: controller.text,
        avatarModel: rightAvatar,
        backgroundColor: ColorsUtils.rgba(220, 232, 255),
        textTypeModel: ChatViewItemTextTypeModel(
            itemBodyTextStyle:
                StylesUtils.customTextStyle(fontSize: 16.sp, color: ColorsUtils.color0000)),
      ));
      controller.text = '';
    });
  }

  Widget buildChatBody(BuildContext context) {
    return GestureDetector(
      onTap: () {
        focusNode.unfocus();
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        child: ChatViewWidget(
          isNeedScrollBottom: true,
          isOpenPreviewImage: true,
          onCreated: onCreated,
          children: data,
        ),
      ),
    );
  }

  void onCreated(ScrollController chatViewWidgetListViewController,
      ChatViewWidgetController chatViewWidgetController) {
    this.chatViewWidgetController = chatViewWidgetController;
  }
}
